﻿<?php
header("Content-type: text/html; charset=utf-8");
$mobile = request('mobile');
if (!$mobile) {
    loginfo('mobile_invalid');
    $msg = array("ip" => "127.0.0.2", "errcode" => "1", "errmsg" => "mobile invalid");
    $sout = json_encode($msg);
    echo utf8_encode($sout);
    exit;
}
loginfo($mobile);
$code = rand(1000, 9999);
$tplvalue = "#code#=" . $code;
$tplid = 31201;
$url = 'http://v.juhe.cn/sms/send?mobile=' . $mobile . '&tpl_id=' . $tplid . '&tpl_value=' . urlencode($tplvalue) . '&key=edd8c1fe68bb60baa8a94b7d16145069';
if (request('debug')) {
    echo $url;
}

$result = curl_get($url);
$aresult = json_decode($result, true);
// {"reason":"error key","result":null,"error_code":10001}
if ($aresult['error_code']) {
    $msg = array("ip" => "127.0.0.2", "errcode" => "1", "errmsg" => "error");
} else {
    $msg = array("ip" => "127.0.0.2", "errcode" => "0", "errmsg" => "ok");
}
$sout = json_encode($msg);
echo utf8_encode($sout);
// 添加数据库
dbadd($mobile, $code);
exit;

// ======================functions==============================
function loginfo($msg) {
    file_put_contents('./log.txt', $msg . PHP_EOL, FILE_APPEND);
}

function request($name, $maxlen = 32) {
    $value = '';
    if (isset($_REQUEST[$name])) {
        $value = $_REQUEST[$name];
        if ($value) {
            $value = htmlentities($value);
            if (strlen($value) > $maxlen) {
                $value = '';
            }
        }
    }
    return $value;
}

/**
 * GET方式获取服务器响应
 * @param {string} $url
 * @return {string|boolen} 成功时返回服务器响应内容，失败则返回false
 */
function curl_get($url) {
    function_exists('curl_init') or die('curl 未安装!');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    if (!curl_exec($ch)) {
        echo curl_error($ch);
        error_log(curl_error($ch));
        $data = '';
    } else {
        $data = curl_multi_getcontent($ch);
    }
    curl_close($ch);
    return $data;
}

function dbadd($mobile, $code) {
    $link = mysqli_connect('106.15.49.79', 'root', 'xyx5659506bT!@#123', 'nodejs');
    mysqli_select_db($link, 'nodejs');
    mysqli_set_charset($link, 'utf8');

    $sqlstmt = "select count(0) as count from t_sms_captcha where mobile='$mobile'";
    $result = mysqli_query($link, $sqlstmt);
    $row = mysqli_fetch_assoc($result);
    $expire = date('Y-m-d H:i:s', strtotime("+5 minutes"));
    if (!$row['count']) {
        $sqlstmt = "insert into t_sms_captcha (mobile, captcha, expire_time) values ('$mobile','$code', '$expire')";
    } else {
        $sqlstmt = "update t_sms_captcha set captcha='$code', expire_time='$expire' where mobile='$mobile'";
    }
    mysqli_query($link, $sqlstmt);
    mysqli_close($link);
}
